import React from 'react';
import { GeoJSON } from 'react-leaflet';
import {
  toNumber, isEmpty, isArray, isString
} from 'lodash';
import setting from './setting';

function isLngLat(lng, lat) {
  return Number(lng) && Math.abs(Number(lng)) > 0 && Math.abs(Number(lng)) < 180
    && Number(lat) && Math.abs(Number(lat)) > 0 && Math.abs(Number(lat)) < 90;
}

function formatLngLat(coords) {
  if (isArray(coords)) return [Number(coords[0]), Number(coords[1])];
  if (isString(coords) && coords.indexOf(' ')) {
    const [lng, lat] = coords.split(' ');
    return [Number(lng), Number(lat)];
  }
  return [0, 0];
}

class LGridHeatLayer extends React.PureComponent {
  // 数据格式化为geoJson
  get geoData() {
    const { data } = this.props;
    if (isEmpty(data)) return [];
    return {
      type: 'FeatureCollection',
      features: data.reduce((pre, item) => {
        const [x1, y1] = formatLngLat(item.leftTop);
        const [x2, y2] = formatLngLat(item.rightBottom);
        if (isLngLat(x1, y1) && isLngLat(x2, y2)) {
          pre.push({
            type: 'Feature',
            properties: {
              tooltip: item.tooltip || '',
              value: toNumber(item.value) || 0
            },
            geometry: {
              type: 'Polygon',
              coordinates: [[[x1, y1], [x2, y1], [x2, y2], [x1, y2], [x1, y1]]],
            }
          });
        }
        return pre;
      }, [])
    };
  }

  // 提示框设置
  get tooltip() {
    const {
      config: {
        tooltip: {
          show, borderColor, borderWidth, font,
          background: { type: backgroundType, backgroundColor, imageUrl }
        }
      }
    } = this.props;
    return {
      show,
      borderColor,
      borderWidth,
      font,
      backgroundType,
      backgroundColor,
      imageUrl
    };
  }

  // 获得区域颜色
  getSpotColor = (value) => {
    const { config: { base: { colors } } } = this.props;

    const set = colors.reduce((pre, item) =>
      (item.start < value && value <= item.end ? item.color : pre), null);
    return set || colors[0].color;
  };

  // 获得区域样式
  getGeoStyle = (feature) => {
    const {
      config: { base: { color, weight } }
    } = this.props;

    return {
      color,
      weight,
      opacity: 1,
      fillOpacity: 1,
      fillColor: this.getSpotColor(feature.properties.value)
    };
  };

  // 获得提示框内容
  getPopupContent = (info) => {
    const {
      borderColor, borderWidth, font, backgroundType, backgroundColor, imageUrl
    } = this.tooltip;
    const myBackground = backgroundType === 'color'
      ? `background-color: ${backgroundColor}` : `background-image: url(${imageUrl})`;

    const infoArray = `${info}`.split(';');
    const text = infoArray.join('<br />');

    return `<div class="map-marker-content" style="${myBackground};
      border: ${borderWidth}px solid ${borderColor};
      color: ${font.color};
      font-size: ${font.fontSize}px;
      font-family: ${font.fontFamily};
      font-weight: ${font.fontWeight};">
     ${text}
    </div>`;
  };

  onEachFeature = (feature, layer) => {
    const { show } = this.tooltip;
    if (show === 'hide') return;

    const popupContent = this.getPopupContent(feature.properties.tooltip);

    if (show === 'click') {
      layer.bindPopup(popupContent, {
        closeButton: false,
        className: 'marker-popup'
      });
      return;
    }
    layer.bindTooltip(popupContent, {
      permanent: show === 'always',
      className: 'marker-tooltip'
    });
  };


  render() {
    const { data } = this.props;
    if (isEmpty(data)) return null;

    return (
      <GeoJSON
        key={Math.floor(Math.random() * 100)}
        data={this.geoData}
        style={(feature) => this.getGeoStyle(feature)}
        onEachFeature={this.onEachFeature}
      />
    );
  }
}

LGridHeatLayer.setting = setting;

export default LGridHeatLayer;
